<template>
  <div>
    <el-card class="box-card defaultTable">
      <el-table v-loading="loading" :data="d.tableData" style="width: 100%">
        <el-table-column prop="name" label="二维码名称" />

        <el-table-column prop="createtime" label="生成时间" />
        <el-table-column align="right" label="操作">
          <template #default="scope">
            <div class="dflex justify-content-end">
              <div class="base-code base-edit">
                <img :src="code" alt="" srcset="" @click="onQrCode" />
              </div>
              <div class="base-edit" @click="onEdit(scope.row)">
                <img :src="edit" alt="" srcset="" />
              </div>
              <div class="base-del" @click="onDel(scope.row.id)">
                <img :src="del" alt="" srcset="" />
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="justify-content-end p10_0"
        :layout="paginationData.layout"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :currentPage="paginationData.currentPage"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 弹出二维码 -->
    <el-dialog
      destroy-on-close
      class="dialogAdapter"
      style="border-radius: 10px"
      v-model="dialogVisible"
      title="生成二维码"
    >
      <el-form :rules="d.rules" ref="ruleFormRef" :model="d.form" label-position="top">
        <el-form-item label="re" prop="re">
          <el-input v-model="d.form.re" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="base_url" prop="base_url">
          <el-input v-model="d.form.base_url" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="danger" @click="submitForm(ruleFormRef)"> 保存 </el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹出 -->
    <DialogQrCodeModel v-if="visible" :visible="visible" type="edit" :editData="editData" @close="visible = false" />
  </div>
</template>

<script lang="ts" setup>
import { APIQrCodexList, APIQrcodexQrcode, APIQrcodexdel } from "@/api/apiSetting"
import code from "@/assets/docs/code.svg"
import { usePagination } from "@/hooks/usePagination"
import dayjs from "dayjs"
import pubsub from "pubsub-js"
import del from "@/assets/docs/del.svg"
import edit from "@/assets/docs/edit.svg"
import DialogQrCodeModel from "@/components/Create/components/dialogQrCodeModel.vue"

import { onBeforeUnmount, onMounted, reactive, ref, watch } from "vue"
// @ts-ignore
import debounce from "@/utils/debounce"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus"
import _ from "lodash"
const ruleFormRef = ref()
const editData = ref({})
const visible = ref<boolean>(false)

const loading = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const d = reactive<any>({
  tableData: [],
  paginationData: {
    total: 0,
    currentPage: 1,
    pageSize: 20
  },
  form: {
    re: "",
    base_url: "https://aiplatform.lnkyeah.com/"
  },
  rules: {
    re: [{ required: true, message: "该项为必填项", trigger: "blur" }],
    base_url: [{ required: true, message: "该项为必填项", trigger: "blur" }]
  }
})

const { paginationData, handleCurrentChange } = usePagination(d.paginationData)

// 监听分页
watch(
  () => paginationData.currentPage,
  () => {
    initModel()
  }
)

// 编辑
const onEdit = (e: any) => {
  // 深拷贝
  const newData = _.cloneDeep(e)
  // 编辑传入参数
  editData.value = { ...newData }
  // 打开编辑
  visible.value = true
}

const onQrCode = () => {
  dialogVisible.value = true
}

const onDel = debounce((id: number) => {
  ElMessageBox.confirm("数据将永久删除，请谨慎操作！是否继续删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const { code } = await APIQrcodexdel({ id })
    if (code === 200) {
      ElMessage({
        type: "success",
        message: "删除成功"
      })
      initModel()
    }
  })
}, 300)

// 提交
const submitForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const { code } = await APIQrcodexQrcode(d.form)
      if (code === 200) {
        dialogVisible.value = false

        ElMessage({
          type: "success",
          message: "保存成功"
        })
      }
    } else {
      console.log("error submit!")

      return false
    }
  })
}, 300)

let UPDATEQRCODELLIST = null as any
onMounted(() => {
  UPDATEQRCODELLIST = pubsub.subscribe("UPDATEQRCODELLIST", () => {
    initModel()
  })
})

onBeforeUnmount(() => {
  pubsub.unsubscribe(UPDATEQRCODELLIST)
})

// 初始化
const initModel = async () => {
  loading.value = true
  const params = {
    page: paginationData.currentPage
  }
  const { data, code } = await APIQrCodexList(params)
  console.log(data)

  if (code !== 200) return
  paginationData.total = data.count
  d.tableData = data.list.map((item: any) => {
    item.createtime = dayjs.unix(item.createtime).format("YYYY-MM-DD HH:mm:ss")
    return item
  })
  loading.value = false
}

onMounted(() => {
  initModel()
})
</script>
<style lang="scss" scoped>
.f14999 {
  margin-bottom: 20px;
  text-align: center;
}

.f14333 {
  font-family: "PingFang SC";
  color: #333;
  font-size: 14px;
  line-height: 24px;
}

#qrcode {
  display: flex;
  justify-content: center;
  align-items: center;
}
.base-edit {
  margin-right: 20px;
  cursor: pointer;
}
.el-card {
  box-shadow: none;
  border: none;

  .base-code {
    // margin-right: 20px;
    cursor: pointer;
  }

  .status {
    .price_icon {
      width: 10px;
      height: 10px;
    }

    /* &-red {
      color: var(--el-color-primary);
    }

    &-green {
      color: #37BB3F;
    } */
  }
}
</style>
